from rest_framework import generics, status
from rest_framework.permissions import IsAuthenticated

from Group.models import TeamDetail, TeamMemberShip
from Group.permission import IsTeamMember, IsTeamAdminOrCreator
from Group.serializers import TeamDetailSerializer, TeamHeaderInfoSerializer, UpdateTeamAnnouncementViewSerializer
from Person.authenticate import MyJSONWebTokenAuthentication
from Utils.BaseResponse import BaseResponse


class TeamDetailView(generics.RetrieveAPIView):
    queryset = TeamDetail.objects.all()
    serializer_class = TeamDetailSerializer
    authentication_classes = [MyJSONWebTokenAuthentication]  # 登录认证
    permission_classes = [IsAuthenticated, IsTeamMember]

    def get(self, *args, **kwargs):
        response = super().get(self, *args, **kwargs)
        if response.status_code == 200:
            return BaseResponse(response.data).success()
        return BaseResponse(response.data, status=status.HTTP_400_BAD_REQUEST).fail()


class TeamHeaderInfoView(generics.RetrieveAPIView):
    queryset = TeamDetail.objects.all()
    serializer_class = TeamHeaderInfoSerializer
    authentication_classes = [MyJSONWebTokenAuthentication]  # 登录认证
    permission_classes = [IsAuthenticated, IsTeamMember]

    def get_object(self, *args, **kwargs):
        pk = self.kwargs['pk']
        return TeamDetail.objects.get(id=pk).team

    def get(self, *args, **kwargs):
        response = super().get(self, *args, **kwargs)
        if response.status_code == 200:
            member = TeamMemberShip.objects.filter(team_id=self.kwargs['pk'], person=self.request.user)
            if not member.exists() :
                response.data['isAdmin'] = False
            else:
                response.data['isAdmin'] = member.first().is_admin
            return BaseResponse(response.data).success()
        return BaseResponse(response.data).fail()


class UpdateTeamAnnouncementView(generics.UpdateAPIView):
    queryset = TeamDetail.objects.all()
    serializer_class = UpdateTeamAnnouncementViewSerializer
    authentication_classes = [MyJSONWebTokenAuthentication]  # 登录认证
    permission_classes = [IsAuthenticated, IsTeamAdminOrCreator]

    def patch(self, request, *args, **kwargs):
        response = super().patch(request, *args, **kwargs)
        if response.status_code == 200:
            return BaseResponse(response.data, status=response.status_code).success()
        return BaseResponse(response.data).fail()

    def put(self, request, *args, **kwargs):
        response = super().put(request, *args, **kwargs)
        if response.status_code == 200:
            return BaseResponse(response.data, status=response.status_code).success()
        return BaseResponse(response.data).fail()
